package com.flainsky.nirvanaplayer.globe;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class DownloadUtils {
	public static enum DataType
	{
		image,
		movie,
		live
	}
	public final static int BUFFER_SIZE = 10240;
	
	public final static String DATA_DIR = Environment
	.getExternalStorageDirectory() + "/nirvana/";
	
	public static String getDataParentPath(DataType type)
	{
		return DATA_DIR+type.toString()+"/";
	}
	
	public synchronized static boolean downloadFile(Context mContext,String strUrl,DataType dt)
	{
		// save before down load
		try
		{
			String mFilePath = DownloadUtils.getDataParentPath(dt);
			String dir = mFilePath + getUrlName(strUrl);
			
			File file = new File(dir);
			if(file.exists())
			{
				return true;
			}
			
			URL  url = new URL(Env.getInstance().getServerAddress()+strUrl);
	        HttpURLConnection conn  = (HttpURLConnection)url.openConnection();
	        conn.setDoInput(true);
	        conn.connect(); 
	        
			InputStream is = conn.getInputStream();;
			if (is != null) {
				File f = new File(mFilePath);
				f.mkdirs();
				f = new File(dir);
				
				if(f.exists())
				{
					Log.d("cache",mFilePath+" exists!");
					is.close();
					return true;
				}
				Log.d("cache",mFilePath+" not exists!");
				
				int readNum;
				byte[] buf = new byte[BUFFER_SIZE];
				FileOutputStream fos = new FileOutputStream(f);
				while ((readNum = is.read(buf, 0, BUFFER_SIZE)) != -1) {
					fos.write(buf, 0, readNum);
				}
				fos.flush();
				fos.close();
				is.close();
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			return false;
		}
		return true;
	}
	
	public static String getUrlName(String url)
	{
		if(url == null)return null;
		int start = 0;
		int end = url.length();
		for(int i = url.length()-1;i>=0;i--)
		{
			if(url.charAt(i) == '/')
			{
				start = i+1;
				break;
			}
		}
		if(end<start)return null;
		return url.substring(start);
	}
}
